<?php
/**
 *	KLF Framework
 *
 *	Written by Kristian Oye <kristianoye@gmail.com> on Oct 23, 2011
 *	Copyright (C) 2010-2011
 */
namespace KLF\System\Web
{
	use KLF\System\Errors\KException;
	use KLF\System\Errors\KEventException;
	use KLF\System\KPropertyContext;
	use KLF\System\Errors\KNotImplementedException;
	use KLF\System\Errors\KArgumentException;
	use KLF\System\Errors\KReadOnlyException;
	use KLF\System\KObject;
	
	/**
	 *  Class KHttpServerUtility
	 *
	 *  @package KLF\System\Web
	 *  @access public
	 *  @author Kristian Oye <kristianoye@gmail.com>
	 *  @since 0.1
	 *  
	 *  @property int $ScriptTimeout The maximum execution time allotted for scripts to run.
	 *  @property string $MachineName The local server name.
	 */
	final class KHttpServerUtility extends KObject
	{
		private static $_Instance;
		
		/**
		 * Returns the computer name on which the script is running.
		 * @var string
		 */
		protected $_rpropMachineName;
		
		/**
		 * Get or set the maximum execution time (in seconds).
		 * @var int
		 */
		protected $_propScriptTimeout;
		
		/**
		 * Set the maximum timeout value for scripts.
		 * 
		 * @param int $val
		 * @return int
		 * @throws KArgumentException
		 */
		public function propScriptTimeout($val=30, $propContext=1)
		{
			if($propContext === KPropertyContext::PROP_SET)
			{
				if (is_int($val) && $val > 1)
					ini_set('max_execution_time',
						($this->_ScriptTimeout = $val));
				else
					throw new KArgumentException("Invalid ScriptTimeout value");
				return $val;
			}
			else
			{
				return $this->_propScriptTimeout;
			}
		}
		
		/**
		 * Constructs a new KHttpServerUtility... but you should not use the 
		 * constructor, you should call KHttpServerUtility::Instance()
		 * 
		 * @throws KException
		 */
		public function __construct()
		{
			if(!isset(self::$_Instance))
			{
				$this->_rpropMachineName = php_uname('n');
				$this->_propScriptTimeout = ini_get('max_execution_time');
			}
			else
			{
				throw new KException("KHttpServerUtility should be accessed with KHttpServerUtility::Instance()");
			}
		}
		
		/**
		 * Returns the singleton instance of the KHttpServerUtility
		 * @return KHttpServerUtility
		 */
		public static function Instance()
		{
			if (!isset(KHttpServerUtility::$_Instance))
			{
				KHttpServerUtility::$_Instance = new KHttpServerUtility();
			}
			return KHttpServerUtility::$_Instance;
		}
		
		/**
		 * Executes a URL within the original request context.
		 * 
		 * @param string $url
		 * @param bool $preserveForm
		 * @throws KNotImplementedException
		 */
		public function Execute($url, $preserveForm=true)
		{
			throw new KNotImplementedException('Execute', $this);
		}
		
		/**
		 * Returns the KHttpServerUtility singleton.
		 * 
		 * @return KHttpServerUtility
		 */
		public static function NewInstance()
		{
			return self::Instance();
		}
	}
}
